//
//  SecondCityViewController.m
//  BreadTravel
//
//  Created by dllo on 15/12/23.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "SecondCityViewController.h"
#import "CJTSecondCityTableViewCell.h"
#import "CJTSecondCityModelHot.h"
#import "CJTSecondCityModelQuanBu.h"

@interface SecondCityViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *array;
@property(nonatomic, strong)NSMutableArray *allCityArray;

@property(nonatomic, strong)NSMutableArray *searchArray;
@property(nonatomic,retain)UISearchBar *mySearchBar;
@property(nonatomic,retain)UISearchController *searchController;


@end

@implementation SecondCityViewController

-(void)viewDidAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor lightGrayColor];
    self.allCityArray = [NSMutableArray array];
    self.array = [NSMutableArray array];
//    UILabel *label = [[UILabel alloc] init];
//    [self.view addSubview:label];
//    [label mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(@30);
//        make.centerX.mas_equalTo(self.view.mas_centerX);
//        make.width.mas_equalTo(@100);
//        make.height.mas_equalTo(@20);
//    }];
//    label.text = @"选 择 城 市";
//    label.textAlignment = NSTextAlignmentCenter;
    self.navigationController.navigationBar.translucent = NO;
//    self.title = @"选 择 城 市";
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.191 green:0.226 blue:0.275 alpha:1.000];

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 15, WIDTH, 20)];
    titleLabel.text = @"选 择 城 市";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    
    [self createTableView];
    
    
    
// appendString
    
}

-(void)createTableHeaderView:(NSMutableArray *)array
{
    CJTSecondCityModelQuanBu *model = array[0];
    
    UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 160)];
    self.tableView.tableHeaderView = aView;
    
    
    self.searchArray = [NSMutableArray array];
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时候隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
//        [searchBar sizeToFit]:设置searchBar位置自适应
    [self.searchController.searchBar sizeToFit];
    
    [aView addSubview:self.searchController.searchBar];
//    self.tableView.tableHeaderView = self.searchController.searchBar;
    
    
    
    
    
    
    UILabel *label1 = [[UILabel alloc] init];
    [aView addSubview:label1];
    label1.text = model.title;
    label1.textAlignment = NSTextAlignmentCenter;
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@10);
        make.top.mas_equalTo(@50);
        make.right.mas_equalTo(@(-10));
        make.height.mas_equalTo(@20);
    }];
    for (int i = 0; i < model.city_list.count; i++) {
        UILabel *label = [[UILabel alloc] init];
        [aView addSubview:label];
        label.tag = 1000 + i;
        label.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [label addGestureRecognizer:tap];
        label.text = model.city_list[i];
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = 1000 + i;
        //设置边宽
        label.layer.borderWidth = 1;
        //设置边颜色
        label.layer.borderColor = [UIColor blackColor].CGColor;
        //设置半径
        label.layer.cornerRadius = 25/2;
        //裁掉边框
        label.layer.masksToBounds = YES;
        
            
        [label  mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(@25);
            make.width.mas_equalTo(@((WIDTH - 80)/3));
            if (i < 3) {
                make.top.equalTo(label1.mas_bottom).offset(10);
                if (i == 0) {
                    
                    make.left.mas_equalTo(@20);
                }else{
                    UILabel *tempLabel = [aView viewWithTag:1000 + i - 1];
                    make.left.equalTo(tempLabel.mas_right).offset(20);
                }
            }else{
                    
                if (i < 6) {
                    make.top.equalTo(label1.mas_bottom).offset(45);
                    if (i == 3) {
                        
                        make.left.mas_equalTo(@20);
                    }else{
                        UILabel *tempLabel = [aView viewWithTag:1000 + i - 1];
                        make.left.equalTo(tempLabel.mas_right).offset(20);
                    }

                }
            }
            
        }];

        
    }
    
    
    
    
}

-(void)createTableView
{
    self.tableView = [[UITableView alloc] init];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view).with.insets(UIEdgeInsetsMake(44, 0, 0, 0));
        
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    [self.tableView registerClass:[CJTSecondCityTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    UIButton *button = [[UIButton alloc] init];
    [self.view addSubview:button];
    button.backgroundColor = [UIColor redColor];
    [button setBackgroundImage:[UIImage imageNamed:@"trip_create_back.png"] forState:(UIControlStateNormal)];
    button.layer.cornerRadius = 30;
    button.layer.masksToBounds = YES;
    button.alpha = 0.4;
    [button addTarget:self action:@selector(buttonAction) forControlEvents:(UIControlEventTouchUpInside)];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(@(-10));
        make.height.mas_equalTo(@60);
        make.width.mas_equalTo(@60);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    
    
    [self getData];
}

-(void)getData
{
    [AFNetworkTool getUrl:@"http://api.breadtrip.com/hunter/products/tabs/v2/" body:nil result:HXJSON headerFile:nil success:^(id result) {
        NSMutableDictionary *bigDic = result;
        NSMutableArray *hot_city_listArray = [bigDic objectForKey:@"hot_city_list"];
        NSMutableArray *hunter_city_listArray = [bigDic objectForKey:@"hunter_city_list"];
        self.allCityArray = hunter_city_listArray;
        for (NSMutableDictionary *dic in hot_city_listArray) {
            CJTSecondCityModelQuanBu *model = [[CJTSecondCityModelQuanBu alloc] initWithDictionary:dic];
            [self.array addObject:model];
        }
        [self createTableHeaderView:(NSMutableArray *)self.array];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
        
    }];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //如果searchController是活动状态,说明是当前正在搜索
    if (self.searchController.active) {
        NSLog(@"~~~~~ count = %lu", self.searchArray.count);
        return self.searchArray.count;
    }
    else {
        return self.allCityArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CJTSecondCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (self.searchController.active) {
        cell.cityName = self.searchArray[indexPath.row];
    }else{
        cell.cityName = self.allCityArray[indexPath.row];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchController.active) {
        NSString *str = self.searchArray[indexPath.row];
        [self.secondCityCVDelegate getCityDetail:str];
        [self dismissViewControllerAnimated:YES completion:^{
            
            
        }];
    }else{
        NSString *str = self.allCityArray[indexPath.row];
        [self.secondCityCVDelegate getCityDetail:str];
    }
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}


-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = [self.searchController.searchBar text];
    NSLog(@"===%@",searchString);
    
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
    if (self.searchArray!= nil) {
        [self.searchArray removeAllObjects];
    }
    //过滤数据
    /*
     对象数组过滤
     
     ios提供了一个filteredArrayUsingPredicate 方法，通过给定条件来进行过滤，过滤后形成一个新的数组。 而NSMutableArray提供了一个filterUsingPredicate方法，在原数组中保留符合条件的数组元素。
     */
    self.searchArray= [NSMutableArray arrayWithArray:[self.allCityArray filteredArrayUsingPredicate:preicate]];
    NSLog(@"searchArray===%@",self.searchArray);
    
        
    //刷新表格
    [self.tableView reloadData];
    
}





//-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
//    
//    NSString *searchString = [self.searchController.searchBar text];
//    
//    NSLog(@"===%@",searchString);
//    
//    [self.searchArray removeAllObjects];
//    for (int i = 0; i< self.allCityArray.count; i++) {
//    
//        
//        //rangeOfString:方法是在movieName中搜索是否包含searchText
//        //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
//        //NSNotFound 表示请求操作的某个内容没有发现
//        if ([self.allCityArray[i] rangeOfString:searchString].location != NSNotFound) {
//        
//            [self.searchArray addObject:self.allCityArray[i]];
//        }
//    }
//    NSLog(@"searchArray===%@",self.searchArray);
//    
//    [self.tableView reloadData];
//    
//}



-(void)tapAction:(UITapGestureRecognizer *)tap
{
    NSInteger tag = tap.view.tag;
    NSLog(@"``== %lu", tag);
    
    if (self.searchController.active) {
        [self dismissViewControllerAnimated:YES completion:^{
            
            
        }];
    }else{
        CJTSecondCityModelQuanBu *model = self.array[0];
        
        [self.secondCityCVDelegate getCityDetail:model.city_list[tag-1000]];
        [self dismissViewControllerAnimated:YES completion:^{
        
        
        }];
    }
}


-(void)buttonAction
{
    [self dismissViewControllerAnimated:YES completion:^{
    
    
    }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
